//Code to disable waiting for enter was taken from Hko at http://www.linuxquestions.org/questions/programming-9/how-do-i-scan-a-character-from-keyboard-without-the-user-having-to-press-enter-134966/

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include "Keyboard.h"
static struct termios oldt;

void restore_terminal_settings(void)
{
    tcsetattr(0, TCSANOW, &oldt);  /* Apply saved settings */
}

// Disables the need for a character to be received by pressing enter.
void disable_waiting_for_enter(void)
{
    struct termios newt;

    /* Make terminal read 1 char at a time */
    tcgetattr(0, &oldt);  /* Save terminal settings */
    newt = oldt;  /* Init new settings */
    newt.c_lflag &= ~(ICANON | ECHO);  /* Change settings */
    tcsetattr(0, TCSANOW, &newt);  /* Apply settings */
    atexit(restore_terminal_settings); /* Make sure settings will be restored when program ends  */
}

// Acts as a keyboard listener accepting key presses instead of waiting for enter.
void *keyboard_listen(void *the_cpu)
{
    CPUPtr temp_cpu = (CPUPtr)the_cpu;
    int interrupt_signal = KEYBOARD_INTERRUPT;
    printf("Keyboard I/O device has been activated.\n");
    disable_waiting_for_enter();
    while (1)
    {
        char c = getchar();
        if (c == EXIT_CHAR) //exit the program if EXIT_CHAR detected.
        {
            exit_func();
        }
        pthread_mutex_lock(temp_cpu->interrupt_lock);
        queue_enqueue(temp_cpu->int_controller, &interrupt_signal, QUEUE_NORM_PRI);
        pthread_mutex_unlock(temp_cpu->interrupt_lock);
        printf("The Keyboard I/O device has generated an interrupt.\n");
    }

    return NULL;
}
